<?php

/**
 * 订单支付
 */

namespace app\order\common;

class PayCommon extends \app\member\common\MemberCommon {

    protected function index() {

        $orderNo = request('', 'order_no', '');

        if (empty($orderNo)) {
            $this->error404();
        }

        $orderNo = urldecode($orderNo);
        $orderNos = explode('|', $orderNo);

        foreach ($orderNos as $key => $vo) {
            $orderNos[$key] = int_format($vo);
        }


        if (empty($orderNos)) {
            $this->error('订单不能存在!');
        }

        $where = [];
        $where['_sql'] = 'order_no in(' . implode(',', $orderNos) . ')';
        $orderList = target('order/Order')->LoadList($where);

        if (empty($orderList)) {
            $this->error('订单不存在!');
        }

        $orderPrice = 0;
        $deliveryPrice = 0;
        $orderSum = 0;
        $orderIds = [];

        foreach ($orderList as $key => $vo) {
            if ($vo['pay_status'] || !$vo['order_status'] || $vo['order_user_id'] <> $this->userInfo['user_id']) {
                unset($orderList[$key]);
                continue;
            }
            $orderIds[] = $vo['order_id'];
            $orderPrice += $vo['order_price'];
            $deliveryPrice += $vo['delivery_price'];
            $orderSum += $vo['order_sum'];
        }

        if (empty($orderList)) {
            $this->error('提交付款的订单无效!');
        }
        arsort($orderIds);

        $orderIds = implode(',', $orderIds);


        $totalPrice = price_format($orderPrice + $deliveryPrice);
        $orderPrice = price_format($orderPrice);
        $deliveryPrice = price_format($deliveryPrice);

        if (!isPost()) {
            $this->pageInfo['name'] = '支付订单';
            $this->setMeta('支付订单');
            $this->setCrumb([
                [
                    'name' => '支付订单',
                    'url' => url()
                ]
            ]);

            if (!empty($orderIds)) {
                $orderGoods = target('order/OrderGoods')->loadList([
                    '_sql' => 'order_id in (' . $orderIds . ')'
                ]);
                $orderGroup = [];
                foreach ($orderGoods as $key => $vo) {
                    $orderGroup[$vo['order_id']][] = $vo;
                }
                foreach ($orderList as $key => $vo) {
                    $orderList[$key]['order_items'] = $orderGroup[$vo['order_id']];
                }
            }

            $payList = target('member/PayConfig')->typeList(true);
            $this->assign('orderNo', $orderNo);
            $this->assign('orderList', $orderList);
            $this->assign('payList', $payList);
            $this->assign('totalPrice', $totalPrice);
            $this->assign('orderPrice', $orderPrice);
            $this->assign('deliveryPrice', $deliveryPrice);
            $this->assign('orderSum', $orderSum);
            $this->otherDisplay();
        } else {
            $type = substr(request('', 'type', '', 'html_in'), 0, 15);
            $target = target('order/Order');

            $orderPay = target('order/OrderPay')->getWhereInfo([
                'user_id' => $this->userInfo['user_id'],
                'order_ids' => $orderIds
            ]);
            if (empty($orderPay)) {
                $orderPayNo = target('order/Order', 'service')->addPay($this->userInfo['user_id'], $orderIds);
                if (!$orderPayNo) {
                    $this->error(target('order/Order', 'service')->getError());
                }
            } else {
                $orderPayNo = $orderPay['pay_no'];
            }
            $config = \Config::get('dux.use');
            $md5 = md5($orderPayNo . $config['safe_key']);
            $target->beginTransaction();
            if (empty($type)) {
                if (!target('order/Order', 'service')->payOrder($orderPayNo, $totalPrice, '余额支付', $orderPayNo, 1)) {
                    $target->rollBack();
                    $this->error(target('order/Order', 'service')->getError());
                    return false;
                }
                $target->commit();
                $this->success('余额支付成功!', url('complete', ['pay_no' => $orderPayNo, 'pay_md5' => $md5]));
            } else {
                $payList = target('member/PayConfig')->typeList();
                $payTypeInfo = $payList[$type];
                if (empty($payTypeInfo)) {
                    $this->error('该支付类型不存在!');
                }
                if ($this->mobile) {
                    if ($payTypeInfo['platform'] <> 'mobile') {
                        $this->error('该支付类型无法使用!');
                    }
                } else {
                    if ($payTypeInfo['platform'] <> 'web') {
                        $this->error('该支付类型无法使用!');
                    }
                }
                $curInfo = reset($orderList);
                $title = $curInfo['order_title'];

                $url = target($payTypeInfo['target'], 'pay')->getUrl([
                    'user_id' => $this->userInfo['user_id'],
                    'order_no' => $orderPayNo,
                    'money' => $totalPrice,
                    'title' => $title,
                    'body' => $title,
                    'app' => 'order',
                ], url('complete', ['pay_no' => $orderPayNo, 'pay_md5' => $md5]));

                if (!$url) {
                    $target->rollBack();
                    $this->error(target($payTypeInfo['target'], 'pay')->getError());
                }
                $target->commit();
                $this->success('即将跳转到支付页面!', $url);
            }
        }
    }

    protected function complete() {
        $payNo = request('get', 'pay_no', 0);
        $payMd5 = request('get', 'pay_md5', 0);
        if (empty($payNo) || empty($payMd5)) {
            $this->error404();
        }

        $config = \Config::get('dux.use');
        $md5 = md5($payNo . $config['safe_key']);
        if ($md5 <> $payMd5) {
            $this->error404();
        }

        $name = '支付成功';
        $desc = '支付完成,请等待系统处理';

        $this->pageInfo['name'] = $name;
        $this->setMeta($name);
        $this->setCrumb([
            [
                'name' => $name,
                'url' => url('', ['pay_no' => $payNo])
            ]
        ]);
        $this->assign('name', '恭喜您已成功支付！');
        $this->assign('desc', $desc);
        $this->otherDisplay();
    }

}